let express = require('express');
let router = express.Router();
let filter = require('../../components/filter');

/**
 * 查询成绩数据 by p 2018-06-15
 *
 * 按指定考试内学生的成绩数据
 *
 */
router.get('/', filter.authorize, function (req, res, next) {
    let params = req.query;

    var limits = "";
    var sql = "";
    var datas = [];
    let user = req.session.user;

    // if (user.roleId !== 1) {
    //     sql = "userId = ?";
    //     datas.push(user.id);
    // }

    if (params.examId > 0) {
        sql += (sql === "" ? "" : " and ") + "examId = ?";
        datas.push(params.examId);
    }

    req.app.db.query("select count(1) as totalCount from score " + (sql === "" ? "" : " where ") + sql + " order by score desc", datas, function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results[0].totalCount === 0) {
            res.json({"success": true, "data": {}, "totalCount": 0});
            return;
        }

        let totalCount = results[0].totalCount;

        if (params.pageNo > 0 && params.pageSize > 0) {
            limits = " limit ?, ?";
            datas.push((params.pageNo - 1) * params.pageSize);
            datas.push(params.pageSize * 1);
        }

        req.app.db.query("select * from score " + (sql === "" ? "" : " where ") + sql + " order by score desc" + limits, datas, function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            res.json({"success": true, "data": results, "totalCount": totalCount});
        });
    });
});

/**
 * 删除成绩信息 by v 2018-06-15
 *
 * 按id删除指定的成绩信息
 */
router.delete('/:id', filter.authorize, function (req, res, next) {
    let params = req.params;
    let user = req.session.user;

    // 查询成绩
    req.app.db.query("select * from score where id = ?", [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "成绩信息错误！"});
            return;
        }

        if (user.id !== 1 && results[0].userId !== user.id) {
            res.json({"success": false, "message": "非录入用户不能删除成绩信息！"});
            return;
        }

        // 删除成绩
        req.app.db.query('delete from score where id = ?', [params.id], function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            res.json({"success": true, "message": global.deleteMsg});
        });
    });
});

module.exports = router;